package com.bwie.filter;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.concurrent.TimeUnit;

/**
 * @Author GaoYiJie
 * @Description
 * @Create 2025/3/12 9:20
 * @Version 1.0
 */
@Component
@Order(1)
public class MyGlobalFilter implements GlobalFilter {

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String url = request.getURI().getPath();

        //白名单
        if (url.contains("register") || url.contains("sendPhoneCode") ||url.contains("login")){
            System.out.println("白名单:"+url);
            return chain.filter(exchange);
        }

        //校验前端token
        String token = request.getHeaders().getFirst("token");
        if (token == null){
            System.out.println("token为空:"+url);
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        //校验后端token
        Claims body = Jwts.parser().setSigningKey("123456").parseClaimsJws(token).getBody();
        Integer userId = body.get("userId", Integer.class);
        String tokenKey = "login_token:"+userId;
        String tokenRedis = stringRedisTemplate.opsForValue().get(tokenKey);
        if (tokenRedis == null){
            System.out.println("token失效:"+url);
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        if (!token.equals(tokenRedis)){
            System.out.println("token错误:"+url);
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        //续期
        stringRedisTemplate.expire(tokenKey,15,TimeUnit.MINUTES);

        return chain.filter(exchange);
    }
}
